package com.taoz.taozrpc.springboot.starter.bootstrap;

import com.taoz.rpc.core.model.ServiceMetaInfo;
import com.taoz.rpc.core.registry.LocalRegistry;
import com.taoz.rpc.core.registry.Registry;
import com.taoz.rpc.core.registry.RegistryFactory;
import com.taoz.taozrpc.springboot.starter.annotation.RpcService;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import java.util.Map;

public class RpcServiceBootstrap {
    private final ApplicationContext applicationContext;

    public RpcServiceBootstrap(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void registerRpcService() throws Exception {
        // 处理所有标注有RpcService注解的类
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RpcService.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            Object serviceImpl = entry.getValue();
            Class<?> serviceImplClass = serviceImpl.getClass();
            RpcService annotation = serviceImplClass.getAnnotation(RpcService.class);
            Class<?> interfaceClass = annotation.interfaceClass();

            // 本地服务注册
            LocalRegistry.register(interfaceClass.getName(), serviceImplClass);

            // 远程服务注册
            Registry registry = RegistryFactory.getRegistry();
            registry.register(ServiceMetaInfo.getInstanceByName(interfaceClass.getName()));
        }
    }
}
